{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ed6d092-e390-4747-928e-ac4dd2b6e602",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n",
      "\u001b[1m  7053312/170498071\u001b[0m \u001b[37m━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[1m3:03:31\u001b[0m 67us/step"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "cifar10=tf.keras.datasets.cifar10\n",
    "(x_train,y_train),(x_test,y_test)=cifar10.load_data()\n",
    "x_train,x_text=tf.cast(x_train,dtype=tf.float32)/255.0,\n",
    "tf.cast(x_test,dtype=tf.float32)/255.0\n",
    "y_train,y_test=tf.cast(y_train,dtype=tf.int32),tf.cast(y_test,dtype=tf.int32)\n",
    "print(\"x_train.shape=\",x_train.shape)\n",
    "print(\"y_train.shape=\",x_train.shape)\n",
    "print(\"x_test.shape=\",x_test.shape)\n",
    "print(\"y_test.shape=\",x_test.shape)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3eb21b56-927c-448c-82c7-6160065e9385",
   "metadata": {},
   "outputs": [],
   "source": [
    "model=tf.keras.models.Sequential([\n",
    "    tfkeras.layers.Conv2D932,kernel_size=(3,3),padding='SAME',\n",
    "activation=tf.nnrelu,input_shape=x_train.shape[1:]),\n",
    "tf.keras.layers.MaxPool2D(pool_size=(2,2),strides=(1,1),padding='SAME'),\n",
    "tf.keras.layers.Dropout(0.2),\n",
    "tf.keras.layers.Conv2D(64,kernel_size=(3,3),padding='SAME',activation=tf.nn.relu),\n",
    "tf.keras.layers.MaxPool2D(pool_size=(2,2),strides=(1,1),padding='SAME'),\n",
    "tf.keras.layers.Dropout(0.2),\n",
    "tf.keras.layers.Flatten(),\n",
    "tf.keras.layers.Dense(512,activation='relu'),\n",
    "tf.keras.layers.Dropout(0.2),\n",
    "tf.keras.layers.Dense(256,activation='relu')\n",
    "tf.keras.layers.Dropout(0.5),\n",
    "tf.keras.layers.Dense(10,activation='softmax')])\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4bc1f14-0bb0-46e6-983b-5a3d9a41a245",
   "metadata": {},
   "outputs": [],
   "source": [
    "model.compile(optimizer='adam',\n",
    "loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n",
    "metrics=['sparse_categorical_accuracy'])\n",
    "history=model.fit(x_train,y_train,batch_size=128,epochs=10,validation_split=0.2)\n",
    "model.evaluate(x_test,y_test,batch_size=64,verbose=2)          "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0671b926-6d7a-4adf-bf13-d5ba26a2b591",
   "metadata": {},
   "outputs": [],
   "source": [
    "loss=history.history['loss']\n",
    "acc=history.history['sparse_categorical_accuracy']\n",
    "val_loss=history.history['val_loss']\n",
    "val_acc=history.history['val_sparse_categorical_accuracy']\n",
    "plt.figure(figsize=(10,3))\n",
    "plt.subplot(121)\n",
    "plt.plot(loss,color='b',label='train')\n",
    "plt.plot(val_loss,color='r',label='validate')\n",
    "plt.ylabel('loss')\n",
    "plt.legend()\n",
    "plt.subplot(122)\n",
    "plt.plot(acc,color='b',label='train')\n",
    "plt.plot(val_acc,color='r',label='validate')\n",
    "plt.ylabel('Accuracy')\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02ee7412-3d8f-420a-a891-54f9d3314c8a",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure()\n",
    "for i in range(10):\n",
    "    n=np.radom.randint(1,10000)\n",
    "    plt.subplot(2,5,i+1)\n",
    "    plt.axis(\"off\")\n",
    "    plt.rcParams['font.sans-serif']=['SimHei']\n",
    "    plt.imshow(x_test[n],cmap='gray')\n",
    "    demo=tf.reshape(x_test[n],(1,32,32,3))\n",
    "    y_pred=np.argmax(model.predict(demo))\n",
    "    title=\"标签值：\"+str((y_test.numpy())[n,0])+\"\\n 预测值：\"+str(y_pred)\n",
    "    plt.title(title)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0770bcae-6367-44dd-97b8-4096fab76773",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
